package com.wyp168.socket.tcp.socketDemo01;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server
{
    public static void main(String[] args) throws IOException {
        Socket socket = null;
        InputStream inputStream = null;
        ServerSocket serverSocket = null;
        try {
            //在本机的9999端口监听，等待连接[要求9999端口没有被占用]
            serverSocket = new ServerSocket(9999);
            System.out.println("服务器端 Sockcet Server 监听9999端口，等待连接");
            //当没有客户端连接9999端口是，程序会 阻塞，等待连接
            socket = serverSocket.accept();
            //如果有客户端连接9999端口，则会返回Socket对象实例

            System.out.println("服务器端 socket: " + socket);

            //IO读取
            //通过 socket.getInputStream() 读取 客户端写入到数据通道的数据，并打印
            inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];

            int readLen = 0;
            while ((readLen = inputStream.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, readLen));  //根据读取到的实际长度，显示字符串
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
                if (serverSocket != null) {
                    serverSocket.close();
                }
                System.out.println("服务端 socket资源关闭");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
